<template>
  <div>
    <div class="pageTopTitle">客户管理</div>
    <div class="app-container">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
        <el-form-item label="客户名称" prop="name">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入客户名称"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="app-container mt20">
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button icon="el-icon-upload2" plain size="mini" type="info" @click="handleImport">导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="clientList">
        <el-table-column label="客户编号-名称" prop="serialNumber" width="140">
          <template slot-scope="scope">
            <div>{{ scope.row.serialNumber }}</div>
            <div class="f-w-bold">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="客户类型" prop="type" width="140"/>
        <el-table-column label="客户地址" prop="area" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.area }}</div>
            <div class="fs-12">{{ scope.row.address }}</div>
          </template>
        </el-table-column>
        <el-table-column label="最新跟进">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleAddFollowUp(scope.row)"
            >新增跟进
            </el-button>
            <div style="background-color: #f5f5f5;padding: 5px;font-size: 12px;color: #999;width: fit-content">
              {{ scope.row.latestRecord || '暂无跟进记录' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期限" prop="createAt" width="200">
          <template slot-scope="scope">
            <div class="status-tag suc">有效期内</div>
            <div class="fs-12">{{ scope.row.startAt }} ~ {{ scope.row.endAt }}</div>
          </template>
        </el-table-column>
        <el-table-column class-name="small-padding fixed-width" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              plain
              size="small"
              type="primary"
              @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-button
              plain
              size="small"
              type="primary"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />

      <!-- 添加或修改客户对话框 -->
      <el-drawer
        :title="title"
        :visible.sync="open"
        size="35%"
      >
        <div class="drawer-content">
          <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
            <el-form-item label="客户类型 - 编号" prop="type">
              <el-col :span="8">
                <el-select v-model="form.type" placeholder="客户类型"
                           @change="handleTypeChange"
                >
                  <el-option v-for="item in clientTypeList" :key="item.code" :label="item.name" :value="item.name"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="2" style="text-align: center">-</el-col>
              <el-col :span="14">
                <el-input v-model="form.serialNumber" disabled placeholder="客户编号"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item :label="form.type === '个人客户' ? '客户姓名' : '客户名称'" prop="name">
              <el-input v-model="form.name" :placeholder="form.type === '个人客户' ? '客户姓名' : '客户名称'"/>
            </el-form-item>
            <div v-if="form.type === '个人客户'">
              <el-form-item label="性别 - 联系方式" required>
                <el-col :span="8">
                  <el-select v-model="form.contactList[0].sex" placeholder="性别" size="small">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="2" style="text-align: center">-</el-col>
                <el-col :span="14">
                  <el-input v-model="form.contactList[0].phone" maxlength="11" placeholder="联系方式"/>
                </el-col>
              </el-form-item>
              <el-form-item label="工作单位">
                <el-input v-model="form.contactList[0].company" placeholder="工作单位"/>
              </el-form-item>
              <el-form-item label="职位 - 微信">
                <el-col :span="8">
                  <el-input v-model="form.contactList[0].job" placeholder="职位"/>
                </el-col>
                <el-col :span="2" style="text-align: center">-</el-col>
                <el-col :span="14">
                  <el-input v-model="form.contactList[0].wechat" placeholder="联系微信"/>
                </el-col>
              </el-form-item>
            </div>
            <el-form-item label="客户地址" prop="city">
              <el-cascader
                v-model="selectedOptions"
                :options="options"
                placeholder="客户地址"
                style="width: 100%;"
                @change="handleAreaChange"
              >
              </el-cascader>
              <div style="margin-top: 16px;">
                <el-input v-model="form.address" :rows="2" placeholder="详细地址" type="textarea"/>
              </div>
            </el-form-item>

            <div v-if="form.type !== '个人客户'">
              <el-divider>
                <div class="fs-14 f-w-bold">客户联系人信息</div>
              </el-divider>
              <el-alert
                :closable="false"
                show-icon
                title="注意：请务必填写完整的联系人信息（联系人姓名与手机号码为必填项），以便于客户经理及时联系到客户。"
                type="warning"
              >
              </el-alert>
              <div v-for="(contact, index) in form.contactList" :key="index" class="contact-info mt20">
                <div class="contact-item-name">
                  联系人{{ index + 1 }}
                </div>
                <div style="flex: 1;margin-right: 20px">
                  <div style="display: flex;align-items: center;margin-bottom: 12px">
                    <el-col :span="8">
                      <el-input v-model="contact.name" placeholder="姓名" size="small"/>
                    </el-col>
                    <el-col :span="2" style="text-align: center">-</el-col>
                    <el-col :span="14">
                      <el-input v-model="contact.phone" maxlength="11" placeholder="手机号" size="small"/>
                    </el-col>
                  </div>
                  <div style="display: flex;align-items: center;margin-bottom: 12px;">
                    <el-col :span="8">
                      <el-select v-model="contact.sex" placeholder="性别" size="small">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="2" style="text-align: center">-</el-col>
                    <el-col :span="14">
                      <el-input v-model="contact.job" maxlength="11" placeholder="职位" size="small"/>
                    </el-col>
                  </div>
                  <el-input v-model="contact.wechat" placeholder="微信号" size="small"/>
                </div>
                <div class="btn-group">
                  <i class="el-icon-circle-plus-outline" style="color: #165DFF; font-size: 22px; cursor: pointer;"
                     @click="addContact"
                  ></i>
                  <i v-if="index > 0" class="el-icon-remove-outline" style="margin-top: 22px;
                color: #F53F3F; font-size: 22px; cursor: pointer"
                     @click="removeContact(index)"
                  ></i>
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button size="small" style="width: 120px;" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" style="width: 120px;" @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
      <!-- 添加或修改客户跟进记录对话框 -->
      <el-drawer
        :visible.sync="openFollowUp"
        :wrapper-closable="false"
        size="35%"
        title="添加跟进记录"
      >
        <div class="drawer-content">
          <el-form ref="followUpForm" :model="followUpForm" :rules="followUpRules" label-width="80px">
            <el-form-item label="跟进客户" prop="clientId">
              <el-input v-model="followUpForm.clientName" disabled placeholder="请选择客户"></el-input>
            </el-form-item>
            <el-form-item label="跟进方式" prop="method">
              <el-select v-model="followUpForm.method" placeholder="请选择跟进方式" style="width: 100%;">
                <el-option label="微信" value="2"></el-option>
                <el-option label="电话" value="1"></el-option>
                <el-option label="上门拜访" value="3"></el-option>
                <el-option label="邮件" value="4"></el-option>
                <el-option label="其他" value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="followUpForm.method === '3'" label="拜访地址" prop="address">
              <el-input v-model="followUpForm.address" placeholder="请输入拜访地址"/>
            </el-form-item>
            <el-form-item label="跟进内容" prop="content">
              <el-input v-model="followUpForm.content" placeholder="请输入跟进内容" rows="4" type="textarea"/>
            </el-form-item>
            <el-form-item label="跟进图片" prop="images">
              <ImageUpload v-model="followUpForm.images" :limit="3"/>
            </el-form-item>
            <el-form-item label="本次跟进" prop="createAt">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="followUpForm.createAt"
                              type="datetime"
                              format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="请选择本次跟进时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="下次跟进" prop="nextFollowUp">
              <el-date-picker v-model="followUpForm.nextFollowUp"
                              clearable
                              placeholder="请选择下次跟进时间"
                              style="width: 100%"
                              type="date"
                              value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            ·
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button size="small" style="width: 120px;" type="primary" @click="submitFollowUpForm">确 定</el-button>
          <el-button size="small" style="width: 120px;" @click="cancelFollowUp">取 消</el-button>
        </div>
      </el-drawer>

    </div>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                 :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                 :auto-upload="false" drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient } from '@/api/web/client'
import { regionData, codeToText } from 'element-china-area-data'
import { formatDateStr } from '@/utils'
import { listTag } from '@/api/web/tag'

import { addUp } from '@/api/web/followUp'
import { getToken } from '@/utils/auth'

export default {
  name: 'Client',
  data() {
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/web/client/importData'
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      clientList: [],

      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示跟进记录弹出层
      openFollowUp: false,
      // 客户类型
      clientTypeList: [{
        name: '个人客户',
        code: 'PE'
      }, {
        name: '企业客户',
        code: 'CO'
      }, {
        name: '机构客户',
        code: 'OR'
      }, {
        name: '其他',
        code: 'OT'
      }],
      clientTagList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNumber: null,
        name: null,
        type: null,
        area: null,
        provinceCode: null,
        cityCode: null
      },
      options: regionData,
      selectedOptions: [],
      // 表单参数
      form: {},
      // 跟进记录表单参数
      followUpForm: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: '客户类型不能为空', trigger: 'blur' }
        ],
        serialNumber: [
          { required: true, message: '客户编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ]
      },
      // 跟进记录表单校验
      followUpRules: {
        method: [
          { required: true, message: '跟进方式不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '跟进内容不能为空', trigger: 'blur' }
        ],
        createAt: [
          { required: true, message: '跟进时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTagList()
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    getTagList() {
      listTag({ pageSize: 20 }).then(response => {
        this.clientTagList = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    cancelFollowUp() {
      this.openFollowUp = false
      this.followUpForm = {}
      this.resetForm('followUpForm')
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialNumber: null,
        name: null,
        type: null,
        area: null,
        provinceCode: null,
        cityCode: null,
        areaCode: null,
        address: null,
        contactList: [{
          name: null,
          phone: null,
          job: null,
          sex: null,
          wechat: null,
          company: null
        }]
      }
      this.selectedOptions = []
      this.resetForm('form')
    },

    addContact() {
      this.form.contactList.push({
        name: null,
        phone: null,
        job: null,
        sex: null,
        wechat: null
      })
    },

    removeContact(index) {
      this.form.contactList.splice(index, 1)
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleAreaChange(e) {
      // 使用 map 方法将 selectedOptions 中的每个 code 转换为对应的文本
      const locationTexts = this.selectedOptions.map(code => codeToText[code])
      this.form.area = locationTexts.join('-')
      this.form.provinceCode = e[0]
      this.form.cityCode = e[1]
      this.form.areaCode = e[2]
    },

    handleTypeChange(e) {
      const data = this.clientTypeList.find(item => item.name === e)
      // 生成随机编号
      this.form.serialNumber = data.code + formatDateStr(new Date()) + Math.floor(Math.random() * 1000)
    },

    /** 新增跟进记录按钮操作 */
    handleAddFollowUp(row) {
      this.followUpForm = {
        clientName: row.name,
        clientId: row.id,
        channelId: row.channelId,
        method: null,
        address: null,
        content: null,
        createAt: null,
        images: null,
        nextFollowUp: null
      }
      this.openFollowUp = true
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加客户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClient(id).then(response => {
        this.form = response.data
        const provinceCode = this.form.provinceCode
        const cityCode = this.form.cityCode
        const areaCode = this.form.areaCode
        this.selectedOptions = [provinceCode, cityCode, areaCode]
        this.form.area = codeToText[provinceCode] + '-' + codeToText[cityCode] + '-' + codeToText[areaCode]
        this.open = true
        this.title = '修改客户'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(this.form.type === '个人客户'){
            this.form.contactList[0].name = this.form.name
            if (this.form.contactList.every(item => !item.phone)) {
              this.$message.error('客户手机号不能为空')
              return
            }
          }else if (this.form.contactList.length === 0 || this.form.contactList.every(item => !item.name && !item.phone)){
              this.$message.error('请至少添加一个联系人信息')
              return
          }
          if (this.form.id != null) {
            updateClient(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addClient(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    submitFollowUpForm() {
      this.$refs['followUpForm'].validate(valid => {
        if (valid) {
          addUp(this.followUpForm).then(response => {
            this.$modal.msgSuccess('新增跟进记录成功')
            this.openFollowUp = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function() {
        return delClient(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleImport() {
      this.upload.title = '客户导入'
      this.upload.open = true
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('web/client/importTemplate', {}, `客户数据导入模版.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }

  }
}
</script>
<style lang="scss" scoped>
.drawer-content {
  padding: 0 30px 80px 20px;
}

.status-tag {
  position: relative;
  font-size: 12px;
  font-weight: bold;
  padding-left: 14px;
  color: #333;

}

.suc::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #00B42A;
  transform: translateY(-50%);
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  text-align: right;
  padding: 16px;
  width: 100%;
  border-top: 1px solid #eee;
  background-color: #fff;
}

::v-deep .el-form-item__label {
  font-weight: 500 !important;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0 0 4px 0 !important;
}

.contact-info {
  display: flex;
  align-items: center;
  margin-bottom: 30px;

  .contact-item-name {
    // 文字竖直排列
    width: 20px;
    margin-right: 20px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #165DFF;
    color: #165DFF;
    padding: 12px 0;
  }

  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }
}


::v-deep .el-divider--horizontal {
  margin: 40px 0 !important;
}

</style>
